package com.ego.service.impl;

import com.ego.commons.exception.DaoException;
import com.ego.commons.pojo.EasyUIDatagrid;
import com.ego.commons.pojo.EgoResult;
import com.ego.commons.utils.IDUtils;
import com.ego.dubbo.service.TbItemDubboService;
import com.ego.pojo.TbItem;
import com.ego.pojo.TbItemDesc;
import com.ego.service.TbItemService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TbItemServiceImpl implements TbItemService {
    @Reference
    private TbItemDubboService tbItemDubboService;
    @Override
    public EasyUIDatagrid showItem(int page, int rows) {
        List<TbItem> tbItems = tbItemDubboService.selectByPage(rows, page);
        long total = tbItemDubboService.selectCount();
        return new EasyUIDatagrid(tbItems,total);
    }

    @Override
    public EgoResult updateItem(long[] ids, int status) {
        try {
            int i = tbItemDubboService.updateStatusByIds(ids, (byte) status);
            if(i == 1){
                return EgoResult.ok();
            }
        } catch (DaoException e) {
            e.printStackTrace();
        }
        return EgoResult.error();
    }

    @Override
    public EgoResult insertItem(TbItem tbItem, String desc) {
        long id = IDUtils.genItemId();
        Date date = new Date();
        tbItem.setCreated(date);
        tbItem.setUpdated(date);
        // 工具类生成id
        tbItem.setId(id);
        tbItem.setStatus((byte)1);

        TbItemDesc tbItemDesc = new TbItemDesc();
        tbItemDesc.setItemId(id);
        tbItemDesc.setItemDesc(desc);
        tbItemDesc.setCreated(date);
        tbItemDesc.setUpdated(date);

        try {
            int i = tbItemDubboService.insertItem(tbItem, tbItemDesc);
            if(i==1){
                return EgoResult.ok();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return EgoResult.error();
    }

    @Override
    public EgoResult update(TbItem tbItem, String desc) {
        Date date = new Date();
        tbItem.setUpdated(date);

        TbItemDesc tbItemDesc = new TbItemDesc();
        tbItemDesc.setItemId(tbItem.getId());
        tbItemDesc.setItemDesc(desc);
        tbItemDesc.setCreated(tbItem.getCreated());
        tbItemDesc.setUpdated(date);

        try {
            int index = tbItemDubboService.update(tbItem, tbItemDesc);
            if(index==1){
                return EgoResult.ok();
            }
        } catch (DaoException e) {
            e.printStackTrace();
        }
        return EgoResult.error();
    }
}
